package org.japo.java.matisse.samples;

import java.io.File;
import java.io.IOException;

public class VentanaCentradaAsistida extends javax.swing.JFrame {

    // Archivo de bloqueo
    private final String F_BLOQUEO = "instancia.lck";

    /**
     * Creates new form VentanaCentradaAsistida
     */
    public VentanaCentradaAsistida() {
        // Antes de la construcción del interfaz
        iniciarAnterior();
        
        // Construcción del interfaz
        initComponents();

        // Después de la construcción del interfaz
        iniciarPosterior();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ventana centrada");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 284, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 162, Short.MAX_VALUE)
        );

        setSize(new java.awt.Dimension(300, 200));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            activarInstancia();
        } catch (IOException ex) {
            terminarPrograma();
        }
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            desactivarInstancia();
        } catch (IOException ex) {
            terminarPrograma();
        }
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaCentradaAsistida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaCentradaAsistida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaCentradaAsistida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaCentradaAsistida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new VentanaCentradaAsistida().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    private void iniciarAnterior() {
    }

    private void iniciarPosterior() {
    }

    private void activarInstancia() throws IOException {
        // Crea un objeto File a partir del nombre del fichero
        File f = new File(F_BLOQUEO);

        // Comprueba si el fichero fisico existe o no
        boolean existeOK = f.exists();

        // Tramita el resultado de la comprobación
        if (!existeOK) {
            f.createNewFile();
        } else {
            throw new IOException("Ya existe una copia en ejecución");
        }
    }

    public void desactivarInstancia() throws IOException {
        // Crea un objeto File a partir del nombre del fichero
        File f = new File(F_BLOQUEO);

        // Comprueba si el fichero fisico existe o no
        boolean existeOK = f.exists();

        // Tramita el resultado de la comprobación
        if (existeOK) {
            f.delete();
        } else {
            throw new IOException("Hay un problema en la anulación del bloqueo");
        }
    }

    private void terminarPrograma() {
        // Oculta la ventana
        setVisible(false);

        // Libera recursos gráficos
        dispose();

        // Termina el hilo principal
        System.exit(0);
    }
}
